package com.github.thread;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.*;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * Created by zhangcheng03 on 2021-6-18 10:25.
 */
public class ImageDownloader {

    private Logger logger = LoggerFactory.getLogger(ImageDownloader.class);

    public static void main(String[] args) throws IOException, InterruptedException {
        ThreadPoolExecutor executor = new ThreadPoolExecutor(50, 100, 200, TimeUnit.MILLISECONDS,
                new LinkedBlockingDeque<>());

        RestTemplate restTemplate = new RestTemplate();

        HttpHeaders headers = new HttpHeaders();
        headers.add("Authorization", "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJleHAiOjE2MjQwNjcyMzgsInVzZXJJZCI6MSwiYWNjb3VudCI6ImFkbWluIn0.0kMU2bGP8lBLfYQfjooG6MeVJdwSny3DCMcTpiA-jy0");
        headers.add("Content-Type", "application/json");

        HttpEntity<MultiValueMap> httpEntity = new HttpEntity<>(null, headers);

        ResponseEntity<String> response = restTemplate.exchange("http://10.68.26.39:12356/qcp/api/checkResult?lineId=&sectionId=&page=2&pageSize=500&startTime=2021-05-01&endTime=2021-05-31", HttpMethod.GET, httpEntity, String.class);
        if (response.getStatusCode() != HttpStatus.OK) {
            System.out.println("登陆异常");
        }

        JSONObject jsonObject = JSONObject.parseObject(response.getBody());
        JSONObject data = jsonObject.getJSONObject("data");

        JSONArray records = data.getJSONArray("records");
        Integer total = data.getInteger("total");
        for (int i = 0; i < records.size(); i++) {
            JSONObject item = records.getJSONObject(i);
            String image_url = item.getString("image_url");
            String filename = image_url.substring(image_url.lastIndexOf("/") + 1);
            DownloadTask downloadTask = new DownloadTask(i,image_url);
            executor.execute(downloadTask);
            Thread.sleep(1000);
        }
        executor.shutdown();
    }
}

class DownloadTask implements Runnable {

    private Logger logger = LoggerFactory.getLogger(DownloadTask.class);

    private int taskNum;
    private String imageUrl;

    DownloadTask(int taskNum, String imageUrl) {
        this.taskNum = taskNum;
        this.imageUrl = imageUrl;
    }

    @Override
    public void run() {
        logger.debug("正在执行task " + taskNum);
        String filename = imageUrl.substring(imageUrl.lastIndexOf("/") + 1);
        try {
            FileUtils.copyURLToFile(new URL(imageUrl), new File("D:\\质检平台5月\\" + filename));
        } catch (IOException e) {
            e.printStackTrace();
        }
        logger.debug("第" + (taskNum + 1) + "张" + filename + "下载完成");

    }
}
